package com.yc.xunlei1;

import org.apache.log4j.Logger;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
import java.util.RandomAccess;

public class DownLoadTask implements Runnable{
    private final int i;
    private long fileSize;
private int threadSize;
private long sizePerThread;
private String url;
private String downloadPath;
private static final Logger log=Logger.getLogger(DownLoadTask.class.getName());
private DownLoadPathSizeNotify dlsn;
public DownLoadTask(int i,long fileSize,int threadSize,long sizePerThread,String url,String downloadPath,DownLoadPathSizeNotify dlsn){
    this.fileSize=fileSize;
    this.threadSize=threadSize;
    this.sizePerThread=sizePerThread;
    this.url=url;
    this.downloadPath=downloadPath;
    this.i=i;
    this.dlsn=dlsn;
}
    @Override
    public void run() {
    //计算此线程要下载的起始和终位置
        long start=i*sizePerThread;
        long end=(i+1)*sizePerThread - 1;//最后一个线程要下载的终止位置
        RandomAccessFile raf=null;
        BufferedInputStream bis=null;
        try {
            raf=new RandomAccessFile(downloadPath,"rw");
            raf.seek(start);
            //开始下载 Range请求头
            //创建URL对象
            URL u=new URL(url);
            //打开连接
            HttpURLConnection connection=(HttpURLConnection) u.openConnection();
            //设置请求头
            connection.setRequestProperty("Range","bytes="+start+"-"+end);
            //获取响应码
            connection.connect();
            bis =new BufferedInputStream(connection.getInputStream());
            byte[]bs=new byte[10*1024];
            int length=-1;
            while ((length=bis.read(bs,0,bs.length))!=-1){
                raf.write(bs,0,length);
                log.info(Thread.currentThread().getName()+"下载了"+length+"字节");
                if (dlsn!=null){
                    dlsn.notifySize(length);
                }
            }
            log.info(Thread.currentThread().getName()+"下载完毕");
        }
    catch (Exception e){
        e.printStackTrace();
        log.error("下载异常"+e);
        }finally {
            if (bis !=null){
                try {
                    bis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (raf != null){
                try {
                    raf.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
